{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a4b3788c",
   "metadata": {},
   "source": [
    "# isinstance举例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "972cc953",
   "metadata": {},
   "outputs": [],
   "source": [
    "class A:\n",
    "    pass\n",
    "\n",
    "class B(A):  # B 继承 A\n",
    "    pass\n",
    "\n",
    "class C(B):  # C 继承 B（间接继承 A）\n",
    "    pass\n",
    "\n",
    "class D(C):  # D 继承 C（间接继承 B、A）\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "76d51542",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "# 创建各 class 的实例\n",
    "a = A()\n",
    "b = B()\n",
    "c = C()\n",
    "d = D()\n",
    "# isinstance判断\n",
    "print(isinstance(b, A))  # True（B 继承 A，b 是 A 的间接实例）\n",
    "print(isinstance(c, B))  # True（C 继承 B，c 是 B 的间接实例）\n",
    "print(isinstance(c, A))  # True（C 间接继承 A，c 是 A 的间接实例）\n",
    "print(isinstance(d, A))  # True（D 间接继承 A，d 是 A 的间接实例）\n",
    "# 反向判断（子类实例不属于“子父类关系”中的父类实例）\n",
    "print(isinstance(a, B))  # False（A 是 B 的父类，a 不是 B 的实例）\n",
    "print(isinstance(b, C))  # False（B 是 C 的父类，b 不是 C 的实例）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea8562d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 示例1：判断类是否是自身的子类（Python 规定：任何类都是自身的子类）\n",
    "print(issubclass(A, A))  # True\n",
    "print(issubclass(B, B))  # True\n",
    "\n",
    "# 示例2：判断直接继承关系\n",
    "print(issubclass(B, A))  # True（B 直接继承 A）\n",
    "print(issubclass(C, B))  # True（C 直接继承 B）\n",
    "print(issubclass(D, C))  # True（D 直接继承 C）\n",
    "# 示例3：判断间接继承关系\n",
    "print(issubclass(C, A))  # True（C 间接继承 A）\n",
    "print(issubclass(D, B))  # True（D 间接继承 B）\n",
    "print(issubclass(D, A))  # True（D 间接继承 A）\n",
    "# isinstance 关注对象与类的关系（对象是否属于类的实例）。\n",
    "# issubclass 关注类与类的关系（类是否是另一个类的子类）。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6a16899",
   "metadata": {},
   "source": [
    "# cast用法\n",
    "什么是Typing Cast？\n",
    "typing.cast()是一个特殊的\"运行时无操作\"函数，主要用于告诉静态类型检查器某个值应该被视为特定类型。它并不执行实际的类型转换，而是为类型检查器提供类型提示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "8c972722",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'id': 1, 'name': 'Alice', 'is_active': True}]\n"
     ]
    }
   ],
   "source": [
    "from typing import cast, List, Any\n",
    "from json import loads\n",
    "\n",
    "def parse_users(json_data: str) -> List[dict]:\n",
    "    # json.loads返回Any类型，我们确定它是用户列表\n",
    "    users = cast(List[dict], loads(json_data))\n",
    "    return [user for user in users if user.get('is_active')]\n",
    "\n",
    "# 示例\n",
    "json_str = '[{\"id\": 1, \"name\": \"Alice\", \"is_active\": true}, {\"id\": 2, \"name\": \"Bob\", \"is_active\": false}]'\n",
    "active_users = parse_users(json_str)\n",
    "print(active_users)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "258f264d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "父类初始化的 messages: ['你好', '世界']\n",
      "父类接收的额外参数: {'author': '测试', 'version': 1.0}\n",
      "子类自己的属性: 这是子类属性\n"
     ]
    }
   ],
   "source": [
    "from typing import cast\n",
    "\n",
    "\n",
    "# 定义一个父类（类似 ChatPromptTemplate）\n",
    "class Parent:\n",
    "    def __init__(self, messages: list, **kwargs):\n",
    "        self.messages = messages\n",
    "        self.extra = kwargs  # 存储额外参数\n",
    "\n",
    "\n",
    "# 子类继承 Parent\n",
    "class Child(Parent):\n",
    "    def __init__(self, messages: list,** kwargs):\n",
    "        # 用 cast 告诉类型检查器：super() 返回的父类是 Parent 类型\n",
    "        cast(\"type[Parent]\", super()).__init__(messages=messages, **kwargs)\n",
    "        # 子类自己的初始化逻辑\n",
    "        self.child_attr = \"这是子类属性\"\n",
    "\n",
    "\n",
    "# 运行测试\n",
    "if __name__ == \"__main__\":\n",
    "    # 创建子类实例\n",
    "    messages = [\"你好\", \"世界\"]\n",
    "    child = Child(messages, author=\"测试\", version=1.0)\n",
    "    \n",
    "    # 验证结果\n",
    "    print(\"父类初始化的 messages:\", child.messages)  # 输出：['你好', '世界']\n",
    "    print(\"父类接收的额外参数:\", child.extra)        # 输出：{'author': '测试', 'version': 1.0}\n",
    "    print(\"子类自己的属性:\", child.child_attr)      # 输出：这是子类属性"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "696123be",
   "metadata": {},
   "source": [
    "# 海象运算符\n",
    "Python 3.8 及以上版本支持的海象运算符（:=）\n",
    "源码节选\n",
    "```python\n",
    "if var_config := var_child_runnable_config.get():\n",
    "```\n",
    "先尝试从 var_child_runnable_config 中获取值并赋值给 var_config，然后判断这个值是否为 “真”（即非空、非零等）。\n",
    "先var_config = var_child_runnable_config.get()\n",
    "然后if var_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c117c01b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# var_config = var_child_runnable_config.get()  # 先赋值\n",
    "# if var_config:  # 再判断\n",
    "#     # 执行后续逻辑"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f40bdff2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "有效数字：6\n"
     ]
    }
   ],
   "source": [
    "# 先赋值，在判断\n",
    "# 第一步：获取用户输入\n",
    "user_input = input(\"请输入一个正整数：\")\n",
    "\n",
    "# 第二步：判断是否有效（非空且是数字）\n",
    "if user_input and user_input.isdigit():\n",
    "    # 第三步：如果有效，转换为整数并使用\n",
    "    num = int(user_input)\n",
    "    print(f\"有效数字：{num}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "e2e0428c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "有效数字：6\n"
     ]
    }
   ],
   "source": [
    "# 一步完成：获取输入 → 存变量 → 判断有效性\n",
    "if (user_input := input(\"请输入一个正整数：\")) and user_input.isdigit():\n",
    "    # 直接使用变量（已确认有效）\n",
    "    print(f\"有效数字：{int(user_input)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "950a33ba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件前10字符： 我是一个长文本串，用\n"
     ]
    }
   ],
   "source": [
    "# 打开文件读取内容\n",
    "with open(\"test.txt\", \"r\") as f:\n",
    "    content = f.read()  # 先存内容\n",
    "\n",
    "# 判断内容是否非空\n",
    "if content:\n",
    "    print(\"文件前10字符：\", content[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "426fbfb9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件前10字符： 我是一个长文本串，用\n"
     ]
    }
   ],
   "source": [
    "with open(\"test.txt\", \"r\") as f:\n",
    "    # 读内容 → 存变量 → 判断非空，一步完成\n",
    "    if content := f.read():\n",
    "        print(\"文件前10字符：\", content[:10])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain-course (3.10.12)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
